package com.cychat.mall.service.impl;

import com.Cychat.commons.entity.pojo.Product;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cychat.mall.mapper.ProductMapper;
import com.cychat.mall.params.SubStock;
import com.cychat.mall.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Auther: 刘俊  <br/>
 * Date: 2025-10-30:下午 2:22  <br/>
 * Description: 商品服务实现类
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {
//    @Autowired
//    private RedisTemplate<String, Integer> redisTemplate;
//
//    @Transactional(rollbackFor = Exception.class)
//    @Override
//    public void subStock(ArrayList<SubStock> subStocks) {
//        //1.获取所有商品ID
//        List<Integer> ids = subStocks.stream().map(SubStock::getProductId).toList();
//        //2.根据商品ID查询所有商品
//        List<Product> products = baseMapper.selectBatchIds(ids);
//
//        for (Product product : products) {
//            //用product的id与subStock中的productId比较得到对应的库存subStock
//            SubStock subStock = subStocks.stream()
//                    .filter(s -> s.getProductId().equals(product.getProductId()))
//                    .findFirst()
//                    .orElse(null);
//            //将每个商品的库存存进redis
////            redisTemplate.opsForValue().set("stock:" + product.getProductId(), product.getStock());
//            //3.判断库存是否充足
//            if (product.getStock() < subStock.getStock()) {
//                throw new RuntimeException("库存不足");
//            }
//
//            //4.更新库存
//            product.setStock(product.getStock() - subStock.getStock());
//            System.out.println(1/0);//测试事务回滚
//            //5.更新销量
//            product.setSales(product.getSales() + subStock.getStock());
//            //7.更新修改时间
//            product.setUpdateTime(new Date());
//            //8.执行更新操作
//            baseMapper.updateById(product);
//        }
//    }
}
